﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxUploadControl;
using DevExpress.Web.ASPxClasses.Internal;
using System.IO;
using System.Web.Caching;
using ZX.EHR.ResumeParseLib;
using ZX.EHR.Library;
using ZX.DBModule;
using System.Configuration;
using ZX.Web.UI.Controls;

namespace ZX.WebApp.EHR
{
    public partial class hrUploadResume :BasePage
    {
        const int ThumbnailSize = 100;
        static IList<ResumeParsedInfo> listResumes = null; //所有上传简历信息
        static IList<string> listContent = null; //所有简历内容
        static string resumeSource = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                UploadControl.ShowProgressPanel = true;
            }
            else
            {
                //获取简历来源信息
                object o = ConfigurationManager.GetSection("resumeSourceConfig");
                ResumeSourceTypesConfig config = o as ResumeSourceTypesConfig;
                ResumeSouceTypeCollection collections= config.ResumeSourceTypes;
                foreach(ResumeSourceTypeElement element in collections )
                {
                    object name= element.GetPropertyValue("Name");
                    object source = element.GetPropertyValue("Source");
                    this.DropDownListResume.Items.Add(new ListItem(name.ToString(), source.ToString()));
                }
                if (this.DropDownListResume.Items.Count > 0) this.DropDownListResume.SelectedIndex = 0;
                ////获取简历类别
                //try
                //{
                //    ZX.EHR.Library.hrCandidateCategory instance = ZX.Common.Globals.getEntity("hrCandidateCategory") as ZX.EHR.Library.hrCandidateCategory;
                //    ZX.BLL.Extend.BaseBussnies hrBll = new ZX.BLL.Extend.BaseBussnies(instance);
                //    IList<BaseEntity> list = hrBll.GetEntitys();
                //    foreach (BaseEntity entity in list)
                //    {
                //        ZX.EHR.Library.hrCandidateCategory hrcategory = entity as ZX.EHR.Library.hrCandidateCategory;
                //        this.DropDownListResumeType.Items.Add(new ListItem(hrcategory.CategoryName, hrcategory.ID.ToString()));
                //    }
                //    if (this.DropDownListResumeType.Items.Count > 0) this.DropDownListResumeType.SelectedIndex = 0;
                //}
                //catch { }
            }

            string flag = this.GetStringFromQueryString("flag", "");
            if (flag.Trim() =="save")
            {
                string requirementId = this.GetStringFromQueryString("requirementid", "");
                //string resumeType = this.GetStringFromQueryString("resumetype", "");
                if (listResumes == null || listResumes.Count == 0) return;
                if (requirementId.Trim() == string.Empty) return;
                this.SaveData(requirementId);
            }
        }

        protected void UploadControl_FileUploadComplete(object sender,
       FileUploadCompleteEventArgs e)
        {
            try
            {
                e.CallbackData = SavePostedFiles(e.UploadedFile);
            }
            catch (Exception ex)
            {
                e.IsValid = false;
                e.ErrorText = ex.Message;
            }
        }

        string SavePostedFiles(UploadedFile uploadedFile)
        {
            if (!uploadedFile.IsValid)
                return string.Empty;

            string strResumeSource = this.Request.Form["DropDownListResume"];
            FileInfo fileInfo = new FileInfo(uploadedFile.FileName);
            string resFileName = Request.PhysicalApplicationPath + "EHR/ResumeFiles/" + strResumeSource + "/" + fileInfo.Name;
            uploadedFile.SaveAs(resFileName);
            //解析简历
            IdentifyEncoding getEncoding = new IdentifyEncoding();
            System.Text.Encoding encoding = getEncoding.GetEncoding(getEncoding.GetEncodingName(new FileInfo(resFileName)));
            StreamReader reader = new StreamReader(resFileName, encoding);
            string content = reader.ReadToEnd();
            reader.Close();

            ResumeParsedInfo resume = ParseTools.ExecuteParse(strResumeSource, content);
            if (resume != null)
            {
                if (listResumes == null) listResumes = new List<ResumeParsedInfo>();
                if (listContent == null) listContent = new List<string>();
                listResumes.Add(resume);
                string tempEncodingStr = "<" + encoding.WebName + ">\r\n";//加入编码
                listContent.Add(tempEncodingStr + content);
            }

            RemoveFileWithDelay(uploadedFile.FileName, resFileName, 5);

            string fileLabel = fileInfo.Name;
            string fileLength = uploadedFile.ContentLength / 1024 + "K";
            return string.Format("{0} ({1})|{2}", fileLabel, fileLength, fileInfo.Name);
        }

       

        static void RemoveFileWithDelay(string key, string fullPath, int delay)
        {
            if (HttpUtils.GetCache()[key] == null)
            {
                DateTime absoluteExpiration = DateTime.Now.Add(new TimeSpan(0, delay, 0));
                HttpUtils.GetCache().Insert(key, fullPath, null, absoluteExpiration,
                    Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, new CacheItemRemovedCallback(RemovedCallback));
            }
        }

        static void RemovedCallback(string key, object value, CacheItemRemovedReason reason)
        {
            if (File.Exists(value.ToString()))
                File.Delete(value.ToString());
        }

        protected void SaveData(string requirementID)
        {
            try
            {
                hrCandidate instance = null;
                ZX.BLL.Extend.BaseBussnies hrCandidateBll = null;
                for (int i = 0; i < listResumes.Count; i++)
                {
                    instance = ZX.Common.Globals.getEntity("hrCandidate") as hrCandidate;
                    instance.RequirementID = new Guid(requirementID);
                    instance.ResumeHTML = Server.HtmlEncode(listContent[i]);
                    instance.AddUser = this.User.UserID;
                    instance.AddTime = DateTime.Now;
                    instance.Name = listResumes[i].Name;
                    instance.Gender = listResumes[i].Gender;
                    instance.IDCardNo = listResumes[i].IDCardNO;
                    instance.PhoneNO = listResumes[i].PhoneNO;
                    instance.Email = listResumes[i].Email;
                    instance.Degree = listResumes[i].Degree;
                    if (listResumes[i].BirthDay != string.Empty)
                    {
                        instance.BirthDay = DateTime.Parse(listResumes[i].BirthDay);
                    }
                    instance.NowPosition = listResumes[i].NowPosition;
                    instance.WorkYears = listResumes[i].WorkYears;
                    instance.ID = Guid.NewGuid();
                    hrCandidateBll = new ZX.BLL.Extend.BaseBussnies(instance);
                    hrCandidateBll.Insert();
                }
                HttpContext.Current.Response.Write("0");
                //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "<script>alert('数据保存成功！');window.returnValue=1;</script>", false);
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("1");
                throw ex;
            }
            finally 
            {
                listResumes.Clear();
                listContent.Clear();
            }
        }
    }
}